<template>
  <div class="page-container relative">
    <BaseCollapse title="基础信息">
      <DynamicForm :config="tsConfig" :questions="tsQuestions" ref="tsRef" />
    </BaseCollapse>

    <BaseCollapse class="fileInformation" title="文件信息">
      <DynamicForm v-if="['ADD', 'REVISE', 'VOID', 'EDIT'].includes(state.showType)" :config="tpConfig" :questions="tpQuestions" ref="tpRef" />
      <AddIndex class="tableStyle" @dataValue="getDataValue" v-if="['ADD'].includes(state.showType) || route.query?.applicationType === '1'"></AddIndex>
      <ViewTable class="tableStyle" @dataType="getDataType" v-if="['VIEW', 'AUDIT', 'SIGN'].includes(state.showType)"></ViewTable>
      <ReviseIndex class="tableStyle" @revisedData="getRevisedData" v-if="state.showType == 'REVISE' || route.query?.applicationType === '2'"></ReviseIndex>
      <VoidIndex class="tableStyle" @voidData="getVoidData" v-if="state.showType == 'VOID' || route.query?.applicationType === '3'"></VoidIndex>
    </BaseCollapse>
    <!-- <BaseCollapse v-if="['VIEW'].includes(state.showType)" title="审批记录">
      <AuditRecord />
    </BaseCollapse> -->
    <!-- <BaseCollapse v-if="['AUDIT', 'SIGN'].includes(state.showType)" title="审批意见">
      <DynamicForm :config="tsProposalConfig" :questions="tsProposalQuestions" ref="proposalRef"></DynamicForm>
    </BaseCollapse> -->
    <!-- <BaseCollapse v-if="['AUDIT', 'SIGN'].includes(state.showType)" title="审批流程图"> </BaseCollapse> -->
    <!-- <AuditRecord v-if="['AUDIT', 'SIGN'].includes(state.showType)" /> -->

    <ApprovalDetail v-if="['VIEW', 'SIGN', 'AUDIT'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>
    <div class="space-x-2 w-full text-center my-4 btn">
      <a-button v-if="!['SIGN', 'AUDIT'].includes(state.showType)" @click="cancel">返回</a-button>
      <a-button v-if="['ADD', 'EDIT', 'REVISE', 'VOID'].includes(state.showType)" @click="submit(0)">暂存</a-button>
      <a-button v-if="['ADD', 'VOID', 'REVISE', 'EDIT'].includes(state.showType)" type="primary" @click="submit(1)">提交</a-button>
      <a-button v-if="['VIEW'].includes(state.showType) && [1, 4].includes(state.fileStatus)" type="primary" @click="handleEdit">编辑</a-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import HomeService from './index.service';
import AddIndex from './component/addIndex.vue';
import ViewTable from './component/viewTable.vue';
import ReviseIndex from './component/reviseIndex.vue';
import VoidIndex from './component/voidIndex.vue';
import ApprovalDetail from '@/components/approval-details/index.vue';
import { Modal, Result, message } from 'ant-design-vue';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { reactive, onMounted, onBeforeUnmount, getCurrentInstance, provide, ref } from 'vue';
import { fileAuto, fileGet, fileSave, fileAudit, fileCountersign } from '@/config/api/documentApplication';
import { filter } from 'rxjs/operators';
import { throttle } from 'xe-utils';
import { SELECTSERVE } from '@/mixins/subject/subject-types';
import { useRoute, useRouter } from 'vue-router';
import { regExp } from '@/utils/regExp';

const { query } = useRoute();
const router = useRouter();
const route = useRoute();
const { proxy }: any = getCurrentInstance();
const state = reactive({
  showType: 'ADD',
  fileStatus: null,
  type: null,
  id: null, // 流程单id
  creator: null //流程单创建人id
});

const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

const approvalGoBack = (cb: any) => {
  cb?.();
};
state.showType = route.query.showType as string;
const tsQuestions: any = reactive(HomeService.getQuestions());
const tpQuestions: any = reactive(HomeService.getQuestionsType());
const tsConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const tpConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const tsProposalQuestions = reactive(HomeService.getProposalQuestions());
const tsProposalConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const proposalRef = ref(null);
const tsRef = ref(null);
onMounted(() => {
  if (route.query.applicationType) {
    tpQuestions[0].value = Number(query.applicationType);
    tpQuestions[0].disabled = true;
  }
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }
  if (state.showType == 'ADD') {
    fileAuto().then((result) => {
      if (result.success) {
        // 基本信息
        const data = result.data;
        tsQuestions.forEach((item) => (item.value = data[item.key]));
        state.id = data.id;
        state.creator = data.creator;
      }
    });
  } else if (['AUDIT', 'SIGN', 'VIEW', 'EDIT'].includes(state.showType)) {
    fileGet(route.query.id).then((result) => {
      if (result.success) {
        const data = result.data;
        tsQuestions.forEach((item) => (item.value = data[item.key]));
        state.fileStatus = result.data.status;
        state.type = result.data.type;
        state.id = data.id;
        // state.id = result.data.applyLists[0].id;
      }
    });
  }
});

const subWatch = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res: any) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === SELECTSERVE) {
      if (item.value.value == 1 && item.value.key == 'status') {
        state.showType = 'ADD';
      } else if (item.value.value == 2 && item.value.key == 'status') {
        state.showType = 'REVISE';
      } else if (item.value.value == 3 && item.value.key == 'status') {
        state.showType = 'VOID';
      }
    }
  });

// 编辑展示的申请类型
let viewType: any = ref(null);
function getDataType(val) {
  viewType.value = val;
}

// 新增 编辑数据
const addData: any = ref([]);
function getDataValue(val) {
  addData.value = val;
}

// 修订数据
const revisedData: any = ref([]);
function getRevisedData(val) {
  revisedData.value = val;
}
// 作废数据
const voidData: any = ref([]);
function getVoidData(val) {
  voidData.value = val;
}
const submit = throttle(async function (op) {
  Modal.confirm({
    title: op === 1 ? '是否确定提交' : '是否确定暂存',
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      if (['ADD'].includes(state.showType) || route.query?.applicationType === '1') {
        // 基本信息
        let creatorData = tsRef.value.getDataFrom();
        if (addData.value.length > 0 && creatorData) {
          if (checkData(addData.value, op)) return;
          if (checkLength(addData.value, op)) return;
          let newData = filterData(addData.value);
          const params = {
            op: op === 1 ? 1 : 0,
            type: state.showType === 'ADD' ? 1 : state.type,
            applyLists: newData,
            ...creatorData,
            creator: state.creator,
            id: route.query.id
          };
          fileSave(params).then((result) => {
            if (result.success) {
              message.success(op === 1 ? '提交成功' : '暂存成功');
              router.go(-1);
            }
          });
        } else {
          message.warning('请添加文件信息');
        }
      } else if (['REVISE'].includes(state.showType) || route.query?.applicationType === '2') {
        // 基本信息
        let creatorData = tsRef.value.getDataFrom();
        if (revisedData.value.length > 0 && creatorData) {
          if (checkData(revisedData.value, op)) return;
          if (checkLength(revisedData.value, op)) return;
          let newData = filterData(revisedData.value);
          const params = {
            op: op === 1 ? 1 : 0,
            type: 2,
            applyLists: newData,
            id: state.id,
            ...creatorData,
            creator: state.creator
          };
          fileSave(params).then((result) => {
            if (result.success) {
              message.success(op === 1 ? '提交成功' : '暂存成功');
              router.go(-1);
            }
          });
        } else {
          message.warning('请添加文件信息');
        }
      } else if (['VOID'].includes(state.showType) || route.query?.applicationType === '3') {
        let creatorData = tsRef.value.getDataFrom();
        if (voidData.value.length > 0 && creatorData) {
          if (checkData(voidData.value, op)) return;
          if (checkLength(voidData.value, op)) return;
          let newData = filterData(voidData.value);
          const params = {
            op: op === 1 ? 1 : 0,
            type: 3,
            applyLists: newData,
            ...creatorData,
            creator: state.creator
          };
          fileSave(params).then((result) => {
            if (result.success) {
              message.success(op === 1 ? '提交成功' : '暂存成功');
              router.go(-1);
            }
          });
        } else {
          message.warning('请添加文件信息');
        }
      } else if (['AUDIT', 'SIGN'].includes(state.showType)) {
        let isError;
        await proposalRef.value.isValidateFields().catch((error) => {
          isError = true;
          console.log(error);
        });
        if (isError) return;
        proposalRef.value.onFinish((data) => {
          let { applyResult, remark } = data;

          if (state.showType === 'AUDIT') {
            fileAudit({ id: route.query.id, applyResult, remark, type: state.type }).then((result) => {
              if (result.success) {
                message.success('提交成功');
                router.go(-1);
              }
            });
          } else if (state.showType === 'SIGN') {
            fileCountersign({ id: route.query.id, applyResult, remark, type: state.type }).then((result) => {
              if (result.success) {
                message.success('提交成功');
                router.go(-1);
              }
            });
          }
        });
      }
    }
  });
}, 1000);

// 过滤参数
function filterData(arr) {
  let res = arr.map((item) => {
    if (state.showType === 'REVISE' || route.query?.applicationType === '2') {
      let obj = {
        name: item.name,
        code: item.code,
        directoryId: item.directoryId,
        version: item.version,
        // securityLevel: item.securityLevel,
        isTemplate: item.isTemplate,
        principalId: item.principalId,
        // counterSignIds: item?.counterSignIds,
        keyword: item.keyword,
        mainContent: item.mainContent,
        applyReason: item.applyReason,
        createdTime: item.versions[item.versions.length - 1].createdTime,
        attachmentFile: item.versions[item.versions.length - 1].attachmentFile,
        remark: item.versions[item.versions.length - 1].remark,
        size: item.versions[item.versions.length - 1].size,
        fileSource: item.versions[item.versions.length - 1].fileSource,
        sourceId: item.versions[item.versions.length - 1].id,
        fileId: item.fileId,
        newVersionId: item?.newVersionId
        // newVersionId: item?.versions[item.versions.length - 1].id
      };
      return obj;
    } else {
      let obj =
        state.showType === 'ADD' || route.query?.applicationType === '1'
          ? {
              name: item.name,
              code: item.code,
              id: state.showType === 'EDIT' ? item?.id : null,
              directoryId: item.directoryId,
              version: item.version,
              // securityLevel: item.securityLevel,
              isTemplate: item.isTemplate,
              principalId: item.principalId,
              // counterSignIds: item?.counterSignIds,
              keyword: item.keyword,
              mainContent: item.mainContent,
              applyReason: item.applyReason,
              attachmentFile: item?.attachment[0]?.attachmentFile,
              remark: item?.attachment[0]?.remark,
              size: item?.attachment[0]?.size,
              newVersionId: item?.attachment[0]?.attachmentFile ? item.newVersionId : null,
              fileSource: item?.attachment[0]?.fileSource,
              sourceId: item?.attachment[0]?.fileId
            }
          : {
              name: item.name,
              code: item.code,
              directoryId: item.directoryId,
              version: item.version,
              // securityLevel: item.securityLevel,
              isTemplate: item.isTemplate,
              principalId: item.principalId,
              // counterSignIds: item?.counterSignIds,
              keyword: item.keyword,
              mainContent: item.mainContent,
              applyReason: item.applyReason,
              fileId: item.fileId
            };
      return obj;
    }
  });
  return res;
}

// 必填项参数校验
function checkData(arr, op) {
  let isError;
  if (op === 0) {
    isError = false;
  } else {
    arr.forEach((item) => {
      if (item.name && (state.showType === 'VOID' || route.query?.applicationType === '3') ? true : item.code && item.directoryId && item.version && item.isTemplate !== null && item.principalId) {
        isError = false;
      } else {
        isError = true;
        message.warning('必填项不能为空');
      }
    });
  }
  return isError;
}

// 字符长度检验
const keywordReg = new RegExp(regExp.strLen20);
const applyReasonReg = new RegExp(regExp.strLen20);
const mainContentReg = new RegExp(regExp.len100);
function checkLength(arr, op) {
  let isError;
  if (op === 0) {
    isError = false;
  } else {
    arr.forEach((item) => {
      if (keywordReg.test(item.keyword) && mainContentReg.test(item.mainContent) && applyReasonReg.test(item.applyReason)) {
        isError = false;
      } else {
        isError = true;
        message.warning('字符长度超过限制');
      }
    });
  }
  return isError;
}

function cancel() {
  router.go(-1);
}
function handleEdit() {
  router
    .replace({
      name: 'documentApplicationAddFile',
      query: {
        id: route.query.id,
        showType: 'EDIT',
        applicationType: viewType.value
      }
    })
    .then(() => {
      router.go(0);
    });
}
onBeforeUnmount(() => {
  subWatch && subWatch.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
});
</script>
<style lang="less" scoped>
.btn {
  margin-top: 200px;
}
.fileInformation {
  margin-bottom: 50px;
}
/deep/ .ant-table-thead > tr > th {
  font-weight: 700;
  background-color: #e5eefd;
}
</style>
